//
//  TrainingCourseViewController.m
//  e-Learning
//
//  Created by rimi on 16/6/16.
//  Copyright © 2016年 YJ. All rights reserved.
//

#import "TrainingCourseViewController.h"
#import "MoviePlayerViewController.h"
#import "EncryptTool.h"

@interface TrainingCourseViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *lessonTableView;
    UIView *containerView;
    NSArray *dataSource;
    int currentSelectSectionIndex;
    NSMutableArray *sectionBtnArray;
    NSIndexPath *currentIndexPath;
    UIView *showRightView;
    NSArray *dataArray;
}
@end

@implementation TrainingCourseViewController

#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    currentSelectSectionIndex = 0;
    sectionBtnArray = [@[] mutableCopy];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([[NSString stringWithUTF8String:object_getClassName(self.presentedViewController)] isEqualToString:@"MoviePlayerViewController"]) {
        return;
    }
   
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"数据加载中" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [self.parentViewController presentViewController:alert animated:YES completion:nil];
    containerView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:containerView];
    showRightView = [[UIView alloc] initWithFrame:CGRectMake(Screen_Width/5, Screen_Height/9, Screen_Width/5*4, Screen_Height/9*7)];
    showRightView.backgroundColor = [UIColor whiteColor];
    [containerView addSubview:showRightView];
    
    lessonTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, Screen_Height/9, Screen_Width/5, Screen_Height/9*7) style:UITableViewStylePlain];
    lessonTableView.backgroundColor = [UIColor colorWithRed:109/255.0 green:109/255.0 blue:109/255.0 alpha:1];
    lessonTableView.tableFooterView = [UIView new];
    lessonTableView.scrollEnabled = NO;
    [lessonTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [containerView addSubview:lessonTableView];
    
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_video!lessonList.action")) parameters:nil finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 1) {
            dataSource = responseObject[@"data"];
            [self dealData];
            lessonTableView.dataSource = self;
            lessonTableView.delegate = self;
            [lessonTableView reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
                CustomBtn *btn = sectionBtnArray[currentSelectSectionIndex];
                [self titleBtn:btn];
                [self tableView:lessonTableView didSelectRowAtIndexPath:currentIndexPath];
            });
            
        } else if ([responseObject[@"status"] intValue] == 101){
            NSLog(@"重复登陆 ");
        }
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if ([[NSString stringWithUTF8String:object_getClassName(self.presentedViewController)] isEqualToString:@"MoviePlayerViewController"]) {
        return;
    }
    [sectionBtnArray removeAllObjects];
    currentSelectSectionIndex = 0;
    [containerView removeFromSuperview];
    containerView = nil;
    

}


#pragma mark - ActionEvents

- (void)dealData{
    for (int i = 0; i < dataSource.count; i ++) {
        CustomBtn *titleBtn = [[CustomBtn alloc] initWithFrame:CGRectMake(0, 0, Screen_Width/5, 100) index:i];
        [titleBtn setTitle:dataSource[i][@"name"] forState:UIControlStateNormal];
        [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [titleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        titleBtn.titleLabel.font = [UIFont boldSystemFontOfSize:22];
        titleBtn.titleLabel.numberOfLines = 0;
        titleBtn.backgroundColor = [UIColor whiteColor];
        [titleBtn addTarget:self action:@selector(titleBtn:) forControlEvents:UIControlEventTouchUpInside];
        [sectionBtnArray addObject:titleBtn];
    }
}

- (void)titleBtn:(CustomBtn *)sender{
    if (currentSelectSectionIndex == sender.index) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            sender.backgroundColor = [UIColor redColor];
        } else {
            sender.backgroundColor = [UIColor whiteColor];
        }
        [lessonTableView reloadSections:[NSIndexSet indexSetWithIndex:currentSelectSectionIndex] withRowAnimation:UITableViewRowAnimationNone];
    } else {
        CustomBtn *btn = sectionBtnArray[currentSelectSectionIndex];
        btn.selected = NO;
        btn.backgroundColor = [UIColor whiteColor];
        [lessonTableView reloadSections:[NSIndexSet indexSetWithIndex:currentSelectSectionIndex] withRowAnimation:UITableViewRowAnimationNone];
        sender.selected = YES;
        sender.backgroundColor = [UIColor redColor];
        currentSelectSectionIndex = sender.index;
        [lessonTableView reloadSections:[NSIndexSet indexSetWithIndex:currentSelectSectionIndex] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)enterVideo:(CustomBtn *)sender{
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_video!videoList.action")) parameters:@{@"id":dataArray[sender.index][@"id"],@"uid":[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 101) {
            NSLog(@"重复登陆");
        } else if ([responseObject[@"status"] intValue] == 1) {
            NSArray *videoDataArray = responseObject[@"data"][@"listName"];
            if (videoDataArray.count == 0) {
                //无视频
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该课程没有视频" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            } else {
                //跳转
                NSMutableArray *videoIDs = [@[] mutableCopy];
                NSMutableArray *videoUrls = [@[] mutableCopy];
                for (int i = 0; i < videoDataArray.count; i ++) {
                    [videoIDs addObject:videoDataArray[i][@"id"]];
                    [videoUrls addObject:url([EncryptTool decodeString:videoDataArray[i][@"url"]])];
                }
                MoviePlayerViewController *movieVc = [MoviePlayerViewController new];
                movieVc.playerListArray = videoUrls;
                movieVc.playerListIDArray = videoIDs;
                movieVc.lessonID = responseObject[@"data"][@"course"][@"id"];
                [self presentViewController:movieVc animated:YES completion:nil];
            }
        }
    }];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (currentIndexPath) {
//        cell.textLabel.textColor = [UIColor lightGrayColor];
        currentIndexPath = indexPath;
    }
    cell.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    cell.textLabel.text = dataSource[indexPath.section][@"downClassify"][indexPath.row][@"name"];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [showRightView removeFromSuperview];
    showRightView = nil;
    showRightView = [[UIView alloc] initWithFrame:CGRectMake(Screen_Width/5, Screen_Height/9, Screen_Width/5*4, Screen_Height/9*7)];
    [containerView addSubview:showRightView];
    
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_video!loadCourse.action")) parameters:@{@"id":dataSource[indexPath.section][@"downClassify"][indexPath.row][@"id"],@"numPerPage":@(10),@"pageNum":@(1)} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 101) {
            NSLog(@"重复登陆");
        } else if ([responseObject[@"status"] intValue] == 1){
            dataArray = responseObject[@"data"];
            if (dataArray.count == 0) {
                //没得课程
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该章节没有课程可观看" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [alert dismissViewControllerAnimated:YES completion:nil];
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            } else {
                for (int i = 0; i < dataArray.count; i ++) {
                    UIView *lessonVu = [[UIView alloc] initWithFrame:CGRectMake(Screen_Width*0.05+i*Screen_Width*0.35,Screen_Height*0.05, Screen_Width*0.3, Screen_Height*0.4)];
                    [showRightView addSubview:lessonVu];
                    UIImageView *imageVu = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width*0.3, Screen_Height*0.25)];
                    [imageVu sd_setImageWithURL:[NSURL URLWithString:url(dataArray[i][@"img"])] placeholderImage:nil options:SDWebImageProgressiveDownload];
                    imageVu.layer.borderColor = [UIColor lightGrayColor].CGColor;
                    imageVu.layer.borderWidth = 1;
                    [lessonVu addSubview:imageVu];
                    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, Screen_Height*0.25, Screen_Width*0.3, Screen_Height*0.04)];
                    title.text = dataArray[i][@"lname"];
                    title.font = [UIFont systemFontOfSize:24];
                    title.layer.borderColor = [UIColor lightGrayColor].CGColor;
                    title.layer.borderWidth = 1;
                    [lessonVu addSubview:title];
                    UILabel *teacher = [[UILabel alloc] initWithFrame:CGRectMake(0, Screen_Height*0.29, Screen_Width*0.15, Screen_Height*0.04)];
                    teacher.text = [@"讲师:" stringByAppendingString:dataArray[i][@"teacher"]];
                    teacher.font = [UIFont systemFontOfSize:24];
                    [lessonVu addSubview:teacher];
                    UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(Screen_Width*0.15, Screen_Height*0.29, Screen_Width*0.15, Screen_Height*0.04)];
                    time.font = [UIFont systemFontOfSize:24];
                    time.textAlignment = NSTextAlignmentRight;
                    time.text = [[@"共" stringByAppendingFormat:@"%@",dataArray[i][@"countLession"]] stringByAppendingString:@"课时"];
                    [lessonVu addSubview:time];
                    UILabel *student = [[UILabel alloc] initWithFrame:CGRectMake(0,Screen_Height*0.33, Screen_Width*0.15, Screen_Height*0.04)];
                    student.text = [[dataArray[i][@"student"] stringValue] stringByAppendingString:@"人正在学习"];
                    student.font = [UIFont systemFontOfSize:24];
                    [lessonVu addSubview:student];
                    UILabel *star = [[UILabel alloc] initWithFrame:CGRectMake(0, Screen_Height*0.37, Screen_Width*0.15, Screen_Height*0.04)];
                    star.text = @"😂😂😂😂😂";
                    star.font = [UIFont systemFontOfSize:24];
                    [lessonVu addSubview:star];
                    UILabel *discuss = [[UILabel alloc] initWithFrame:CGRectMake(Screen_Width*0.15, Screen_Height*0.37, Screen_Width*0.15, Screen_Height*0.04)];
                    discuss.text = [[dataArray[i][@"discuss"] stringValue]stringByAppendingString:@"评论"];
                    discuss.font = [UIFont systemFontOfSize:24];
                    discuss.textAlignment = NSTextAlignmentRight;
                    [lessonVu addSubview:discuss];
                    CustomBtn *btn = [[CustomBtn alloc] initWithFrame:CGRectMake(0,0, Screen_Width*0.3, Screen_Height*0.4) index:i];
                    [btn addTarget:self action:@selector(enterVideo:) forControlEvents:UIControlEventTouchUpInside];
                    [lessonVu addSubview:btn];
                }
            }
        }
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return sectionBtnArray[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *cellCount = dataSource[section][@"downClassify"];
    CustomBtn *btn = sectionBtnArray[section];
    if (btn.selected) {
        return cellCount.count;
    } else {
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 100;
}
@end
